"""
The is doc
"""


import logging

from rest_framework import status

from traceback import format_exc
from traceback_with_variables import iter_exc_lines

from .json_response import json_response_utf8


logger = logging.getLogger("log")


# 小程序 只能 展示 七个字的错误
class NoAccess(Exception):
    code = -10001
    msg = "no access: need login, please access /login"


class AdminLoginFail(Exception):
    code = -10002
    msg = "admin login fail"


class ParamsErr(Exception):
    code = -10003
    msg = "参数错误"


class ValueErr(Exception):
    code = -10004
    msg = "变量值错误"


class NameInValid(Exception):
    code = -20001
    msg = "名称格式错误"


class NameExist(Exception):
    code = -20002
    msg = "名称重复"


class NameNotExist(Exception):
    code = -20003
    msg = "名称不存在"


class ObjectExist(Exception):
    code = -20004
    msg = "对象已存在"


class ObjectNotExist(Exception):
    code = -20005
    msg = "对象不存在"


class PhoneInValid(Exception):
    code = -20006
    msg = "手机号码不正确"


class UrlInValid(Exception):
    code = -20007
    msg = "url必须https开头"


class AttrNoChange(Exception):
    code = -20008
    msg = "没有属性变化"


class OnlyReadAttr(Exception):
    code = -20009
    msg = "属性只读"


class NotBindHouse(Exception):
    code = -20010
    msg = "未绑定房屋"


class WxNotRegister(Exception):
    code = -30001
    msg = "用户需要从微信小程序进行注册"


class WxOpenidExist(Exception):
    code = -30002
    msg = "openid重复"


class NullErr(Exception):
    code = -40001
    msg = "值不能为空"


def app_try(func):
    def d(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as _exception:
            lines = []
            lines += list(iter_exc_lines(_exception))
            lines.append(format_exc())
            logger.fatal("\n".join(lines))
            return json_response_utf8(
                {
                    "code": getattr(_exception, "code", -1),
                    "exception": f"{type(_exception).__name__}, {str(_exception)}",
                    "msg": getattr(
                        _exception,
                        "msg",
                        getattr(_exception, "message", "未知错误"),
                    ),
                    "detail": getattr(_exception, "detail", "未知错误"),
                },
                status=status.HTTP_400_BAD_REQUEST,
            )

    return d
